/*
 * @lc app=leetcode.cn id=1046 lang=javascript
 *
 * [1046] 最后一块石头的重量
 */

// @lc code=start
/**
 * @param {number[]} stones
 * @return {number}
 */
var lastStoneWeight = function (stones) {
  const haldInsert = (arr, num) => {
    let l = 0;
    let r = arr.length - 1;
    while (l <= r) {
      let mid = Math.floor((l + r) / 2);
      if (arr[mid] <= num) {
        l = mid + 1;
      } else {
        r = mid - 1;
      }
    }
    arr.splice(l, 0, num);
  };
  stones.sort((a, b) => a - b);
  while (stones.length >= 2) {
    let newItem = stones.pop() - stones.pop();
    if (newItem !== 0) {
      haldInsert(stones, newItem);
    }
  }
  return stones.length === 1 ? stones[0] : 0;
};
// @lc code=end
